import 'dart:convert';

import 'package:dk_flutter_base/dk_core.dart';
import 'package:dk_flutter_base/dk_ui.dart';
import 'package:dk_flutter_module_sale/common/config/page_base_common.dart';
import 'package:dk_flutter_module_sale/common/plugin/bean/bean_handle_cache.dart';
import 'package:dk_flutter_module_sale/common/plugin/bean/bean_open_custom_media.dart';
import 'package:dk_flutter_module_sale/common/plugin/bean/bean_preview_video.dart';
import 'package:dk_flutter_module_sale/common/plugin/bean/bean_record_video.dart';
import 'package:dk_flutter_module_sale/common/plugin/bean/bean_upload_video.dart';
import 'package:dk_flutter_module_sale/common/plugin/plugin_common.dart';
import 'package:dk_flutter_module_sale/common/user_track/user_track.dart';
import 'package:dk_flutter_module_sale/config/route/sale_check_widget_route.dart';
import 'package:dk_flutter_module_sale/sale/Image/image_url.dart';
import 'package:dk_flutter_module_sale/sale/api/sale_check_api.dart';
import 'package:dk_flutter_module_sale/sale/sale_check/room_paint/bean/image_bean.dart';
import 'package:dk_flutter_module_sale/sale/sale_check/room_paint/bean/password_bean.dart';
import 'package:dk_flutter_module_sale/sale/sale_check/room_paint/bean/request_bean.dart';
import 'package:dk_flutter_module_sale/sale/sale_check/room_paint/bean/upload_room_paint_bean.dart';
import 'package:dk_flutter_module_sale/sale/sale_check/room_paint/logic/room_paint_logic.dart';
import 'package:dk_flutter_module_sale/sale/sale_check/room_paint/widget/image_widget.dart';
import 'package:dk_flutter_module_sale/sale/sale_check/room_paint/widget/password_tip_widget.dart';
import 'package:dk_flutter_module_sale/sale/sale_check/room_paint/widget/section_widget.dart';
import 'package:dk_flutter_module_sale/sale/sale_check/room_paint/widget/toast_widget.dart';
import 'package:dk_flutter_module_sale/sale/sale_check/room_paint/widget/two_button_widget.dart';

@ARoute(url: SaleCheckWidgetRoute.SALE_CHECK_ROOM_PAINT_EDIT)
//房态采集
class PageRoomPaintEdit extends CommonPageWithTrack {
  final WidgetOption option;
  PageRoomPaintEdit(this.option) : super();

  @override
  void trackStatistics() {
    UserTrack.trackViewScreen("巡房-房态采集-编辑", null);
  }

  @override
  void onInitState(CommonPageBloc pageBloc, {Map<String, Bloc> extraBlocMap}) {
    RequestBean requestBean = RequestBean.fromJson(this.option.widgetParams);
    pageBloc.dataHttpGet(
        showLoading: false,
        path: SaleCheckApi.roomPaintEditDetail,
        queryMap: {"suiteId": requestBean.suiteId},
        handleResult: (dynamic data) {
          AreaDataBean dataBean = AreaDataBean.fromJson(data);
          pageBloc.switchPage(RoomPaintStatefulWidget(pageBloc,requestBean,dataBean));
        });
  }
}

class RoomPaintStatefulWidget extends StatefulWidget {
  final RequestBean paramBean;
  final CommonPageBloc pageBloc;
  final AreaDataBean dataBean;
  RoomPaintStatefulWidget(this.pageBloc, this.paramBean,this.dataBean);
  @override
  _RoomPaintStatefulWidgetState createState() =>
      _RoomPaintStatefulWidgetState(pageBloc, this.paramBean,this.dataBean);
}

class _RoomPaintStatefulWidgetState extends State<RoomPaintStatefulWidget> {
  final RequestBean paramBean;
  final CommonPageBloc pageBloc;
  DkCenterDialog tipDialog;
  AreaDataBean dataBean;
  CommonPlugin commonPlugin = CommonPlugin();
  Url deleteURL;
  bool isUpLoading = false;
  _RoomPaintStatefulWidgetState(this.pageBloc, this.paramBean,this.dataBean);

  void refresh(){
    pageBloc.dataHttpGet(
        showLoading: true,
        path: SaleCheckApi.roomPaintEditDetail,
        queryMap: {"suiteId": this.paramBean.suiteId},
        handleResult: (dynamic data) {
          setState(() {
            this.dataBean = AreaDataBean.fromJson(data);
          });
        });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: DkAppBar(
          DKAppBarParams.withBackMenu(context, [], title: Text("房态采集"))),
      backgroundColor: Colors.white,
      body: SafeArea(
        bottom: true,
        child: Stack(
          children: <Widget>[
            Container(
              margin: EdgeInsets.only(bottom: 60),
              color: Colors.white,
              child: CustomScrollView(
                physics: ScrollPhysics(),
                slivers: getSliverToBoxAdapters(),
              ),
            ),
            Positioned(
              bottom: 0,
              left: 0,
              right: 0,
              child: this.getBottomWidget(),
            )
          ],
        ),
      ),
    );
  }

  Widget getBottomWidget() {
    return TwoButtonWidget(
      leftTitle: "取消",
      rightTitle: "完成",
      tapAction: (int index) {
        if (index == 0) {
          RouteUtil.popOrCloseCurPage(animated: true, context: context);
        } else {
          this.finishAction();
        }
      },
    );
  }

  List<Widget> getSliverToBoxAdapters() {
    List<Widget> boxAdapters = List<Widget>();
    if (this.dataBean == null) return boxAdapters;
    Widget gap = SliverToBoxAdapter(
        child: Container(
      color: Color(0xFFF7F8FA),
      height: 10,
    ));
    //外部和公共视频
    for (int i = 0; i < this.dataBean.areas.length; i++) {
      AreaBean areaBean = this.dataBean.areas[i];
      if (areaBean.enType == RoomEnvironmentType.RoomEnvironmentTypeOut) {
        boxAdapters.add(SliverToBoxAdapter(
            child: SectionWidget(
          title: areaBean.areaName,
          bottomLineHidden: false,
        )));
        boxAdapters.addAll(videoArea(areaBean));
        boxAdapters.add(gap);
      } else if (areaBean.enType ==
          RoomEnvironmentType.RoomEnvironmentTypeCommon) {
        boxAdapters.add(SliverToBoxAdapter(
            child: SectionWidget(
          canAdd: areaBean.flag,
          title: areaBean.areaName,
          getPasswordText: areaBean.flag ? "获取外门密码" : "",
          tapAction: () {
            getPassWord(areaBean);
          },
          bottomLineHidden: false,
        )));
        boxAdapters.addAll(videoArea(areaBean));
        boxAdapters.add(gap);
      }
    }
    SliverToBoxAdapter separateLine = SliverToBoxAdapter(
      child: Divider(
        height: 0.5,
        indent: 15,
        endIndent: 15,
        color: Color(0xFFEBEBEB),
      ),
    );

    ///房间内部视频
    bool addInnerHeader = false;
    for (int i = 0; i < this.dataBean.areas.length; i++) {
      AreaBean areaBean = this.dataBean.areas[i];
      if (areaBean.enType == RoomEnvironmentType.RoomEnvironmentTypeInner) {
        if (addInnerHeader == false) {
          boxAdapters.add(SliverToBoxAdapter(
              child: SectionWidget(
            title: "房间内部视频",
            bottomLineHidden: false,
          )));
          addInnerHeader = true;
        }
        boxAdapters.add(SliverToBoxAdapter(
            child: SectionWidget(
              titleStyle: TextStyle(
                  color: Color(0xFF666666),
                  fontSize: 14,
                fontWeight: FontWeight.w600
              ),
                canAdd: areaBean.flag,
                title: areaBean.areaName,
                getPasswordText: areaBean.flag ? "获取内门密码" : "",
                tapAction: () {
                  getPassWord(areaBean);
                })));
        boxAdapters.addAll(videoArea(areaBean));
        if (i != this.dataBean.areas.length - 1) {
          boxAdapters.add(separateLine);
        }
      }
    }
    return boxAdapters;
  }

  void getPassWord(AreaBean areaBean) {
    Map<String,dynamic> map = Map();
    if(areaBean.enType == RoomEnvironmentType.RoomEnvironmentTypeCommon) {
      map["suiteId"] = this.paramBean.suiteId;
    } else if(areaBean.enType == RoomEnvironmentType.RoomEnvironmentTypeInner){
      map["suiteId"] = this.paramBean.suiteId;
      map["roomCode"] = areaBean.roomCode;
    }
    this.pageBloc.dataHttpGet(
        path: SaleCheckApi.roomPaintGetPassword,
        queryMap: map,
        handleResult: (dynamic data) {
          PassWordBean bean = PassWordBean.fromJson(data);
          String suffixStr = "  " + bean.suiteAdrr;
          if(areaBean.enType == RoomEnvironmentType.RoomEnvironmentTypeInner) {
            showPasswordTipDialog(
                areaBean.roomCode + suffixStr, RoomPaintLogic.doorTypeStr(areaBean, bean));
          } else {
            showPasswordTipDialog(bean.suiteId + suffixStr, RoomPaintLogic.doorTypeStr(areaBean, bean));
          }
        });
  }

  List<Widget> videoArea(AreaBean areaBean) {
    List<Widget> boxAdapters = List<Widget>();
    int count = 0;
    if (areaBean.flag) {
      count = 1;
    }
    count += areaBean.url.length;
    EdgeInsets padding;
    if (areaBean.enType == RoomEnvironmentType.RoomEnvironmentTypeInner) {
      padding = EdgeInsets.only(left: 10, right: 10, top: 0, bottom: 0);
    } else {
      padding = EdgeInsets.only(left: 10, right: 10, top: 17, bottom: 17);
    }
    SliverPadding sliverPadding = SliverPadding(
      padding: padding,
      sliver: new SliverGrid(
        //Grid
        gridDelegate: new SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 4,
          mainAxisSpacing: 0,
          crossAxisSpacing: 0.0,
          childAspectRatio: 1.0,
        ),
        delegate: new SliverChildBuilderDelegate(
          (BuildContext context, int index) {
            bool lookOnly;
            String imageUrl;
            ///需要上传，
            if(areaBean.flag) {
              if(objNotEmpty(areaBean.recordVideoResultBean) && index == count - 1) {
                lookOnly = false;
                imageUrl = areaBean.recordVideoResultBean.videoFrameImgPath;
              } else if(index == count - 1) {
                lookOnly = true;
                imageUrl = AppNetWorkImage.cameraIcon;
              } else {
                Url uri = areaBean.url[index];
                lookOnly = !uri.isDelete;
                imageUrl = uri.imageUrl;
              }
            } else {
              Url uri = areaBean.url[index];
              if(uri.isDelete) {
                lookOnly = false;
              } else {
                lookOnly = true;
              }
              imageUrl = uri.imageUrl;
            }
            return ImageWidget(
              deleteAction: () {
                if(areaBean.flag) {
                  if(objNotEmpty(areaBean.recordVideoResultBean) && index == count - 1) {
                    setState(() {
                      RoomPaintLogic.deleteNativeVideo([areaBean.recordVideoResultBean]);
                      areaBean.recordVideoResultBean = null;
                    });
                  } else {
                    deleteURL = areaBean.url[index];
                    showDeleteTipDialog();
                  }
                } else {
                  deleteURL = areaBean.url[index];
                  showDeleteTipDialog();
                }
              },
              tapAction: () {
                RoomPaintLogic.paintVideoTapAction(context,areaBean, index, count,this);
              },
              imageURL: imageUrl,
              lookOnly: lookOnly,
            );
          },
          childCount: count,
        ),
      ),
    );
    boxAdapters.add(sliverPadding);
    return boxAdapters;
  }

  void toast(String msg) {
    showWidgetToast(ToastWidget(
      title: msg,
    ));
  }

  bool checkForgetVideoPass() {
    for (int i = 0; i < this.dataBean.areas.length; i++) {
      AreaBean areaBean = this.dataBean.areas[i];
      if (areaBean.flag && objEmpty(areaBean.recordVideoResultBean)) {
        toast("您未上传" + areaBean.areaName + "请上传后在进行提交!");
        return false;
      }
    }
    return true;
  }

  void finishAction() {
    //检查应该上传的视频
    if (checkForgetVideoPass() == false) {
      return;
    }
    //上传视频
    UploadVideoBean uploadVideoBean =
        new UploadVideoBean(picUploadConfig: UploadConfigBean.publicSaleOut());
    List<RecordVideoResultBean> videoList = List();
    for (int i = 0; i < this.dataBean.areas.length; i++) {
      AreaBean areaBean = this.dataBean.areas[i];
      if (objNotEmpty(areaBean.recordVideoResultBean)) {
        videoList.add(areaBean.recordVideoResultBean);
      }
    }

    if(videoList.length == 0){
      toast("您没有需要上传的视频!");
      return;
    }

    uploadVideoBean.videoList = videoList;
    if(isUpLoading) {
      toast("视频正在上传，请稍后。。。");
      return;
    } else {
      isUpLoading = true;
    }
    LoadingDialog loadingDialog = LoadingDialog.create().show(context);
    this.commonPlugin.uploadVideo(
        bean: uploadVideoBean,
        handleResult: (UploadVideoResultBean uploadVideoResultBean) {
          if(uploadVideoResultBean == null) {
            this.cancelLoading(loadingDialog);
            toast("视频上传出错,请重新上传!");
            return;
          }
          if (uploadVideoResultBean.failList.length > 0) {
            this.cancelLoading(loadingDialog);
            toast("视频上传出错,请重新上传!");
            return;
          }
          Map param = RoomPaintLogic.createUploadData(uploadVideoResultBean,videoList,dataBean,this.paramBean.suiteId);
          this.pageBloc.dataHttpPost(
          showFailMsg: true,
              path: SaleCheckApi.roomPaintSave,
              data: param,
              handleResult: (dynamic data) {
                this.cancelLoading(loadingDialog);
                toast("视频上传成功");
                RoomPaintLogic.deleteNativeVideo(videoList);
                RouteUtil.pop(context,result: {"isOK":"1"});
              },
              handleErrorCode: (DefaultResponseData data){
                this.cancelLoading(loadingDialog);
                toast("${data.msg}");//非0000
              },
            handleFailResult: (dynamic data1,dynamic data2){
              this.cancelLoading(loadingDialog);
            }
          );
        });
  }

  void cancelLoading(LoadingDialog loadingDialog){
    loadingDialog.cancel();
    isUpLoading = false;
  }

  void showPasswordTipDialog(String firstName, String secondName) {
    DkCenterDialog pwdTips = DkCenterDialog.create(
      CenterDialogOption(
        (BuildContext context) {
          return PasswordStatelessWidget(
            firstName: firstName,
            secondName: secondName,
            tipName: "我知道了",
            tapAction: () {},
          );
        },
        handleResult: (bool isConfirm) {},
      ),
    );
    pwdTips.show(context);
  }

  void showDeleteTipDialog() {
    if (null == tipDialog) {
      tipDialog = DkCenterDialog.create(
        CenterDialogOption(
          (BuildContext context) {
            return TipDialogWidget(
              TipDialogOption.normalWithContent("您是否确认删除该视频？"),
            );
          },
          handleResult: (bool isConfirm) {
            if (isConfirm) {
              this.pageBloc.dataHttpDelete(
                showFailMsg: true,
                  path: SaleCheckApi.roomPaintVideoDelete + "${deleteURL.id}",
                  handleResult: (dynamic data) {
                    this.refresh();
                  },
                  handleErrorCode: (DefaultResponseData data){
                    toast("${data.msg}");//非0000
                  },
                  showLoading: true);
            }
          },
        ),
      );
    }
    tipDialog.show(context);
  }
}
